package com.anXin.equipment.service.impl;



import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.anXin.equipment.service.EquipmentService;
import com.anXin.model.equipment.Equipment;
import com.anXin.model.equipment.RateZones;
import com.google.gson.Gson;
import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import utils.common.Base64Utils;

import java.beans.ConstructorProperties;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
@Service("equipmentService")
public class EquipmentServiceImpl implements EquipmentService {

    private String clientId="23R46S";
    private String clientSecret="81b3438e284700653e2e3ade30dccfb3";
    private String scope="activity heartrate location nutrition profile settings sleep social weight";
    private String userAuthorizationUri="https://www.fitbit.com/oauth2/authorize";
    private String accessTokenUri="https://api.fitbit.com/oauth2/token";
    private String apiUri="https://api.fitbit.com";
    private String code;
    private String access_token;
    private String refresh_token;
    private String token_type;
    private String user_id;
    @Value("${fitbit.cookie}")
    private static String cookie;


    public static void main(String[] args) throws NacosException {
        ConfigService configService = NacosFactory.createConfigService("localhost:8848");
        String dataId = "anXin-service-equipment-dev.yml";
        String group = "DEFAULT_GROUP";
        String content = configService.getConfig(dataId, group, 5000);
        System.out.println("--"+content.substring(content.indexOf("cookie:")+8).trim()+"--");
//        EquipmentServiceImpl equipmentService = new EquipmentServiceImpl();
//        equipmentService.getToken();
//        Equipment equipment = equipmentService.getEquipment();
//        System.out.println(equipment.getLastSyncTime());
//        RateZones rateZones = equipmentService.getRateZones("2023-07-30");
//        List<HeartRateZones> heartRateZones = rateZones.getHeartRateZones();
//        for (HeartRateZones heartRateZone : heartRateZones) {
//            System.out.println("max"+heartRateZone.getMax());
//            System.out.println("min"+heartRateZone.getMin());
//            System.out.println("name"+heartRateZone.getName());
//
//        }
//        System.out.println(equipmentService.getCalories("today"));
    }


    /**
     * fitbit初始化获取第三方token、user_id等
     */
    @Override
    public void getToken() {
        try {
            ConfigService configService = NacosFactory.createConfigService("111.230.47.140:8848");
            String dataId = "anXin-service-equipment-dev.yml";
            String group = "DEFAULT_GROUP";
            String content = configService.getConfig(dataId, group, 5000);
            String trim = content.substring(content.indexOf("cookie:") + 8).trim();
            // 创建CookieStore并设置Cookie
            CookieStore cookieStore = new BasicCookieStore();
            BasicClientCookie cookie = new BasicClientCookie("Cookie",trim ); // 替换为实际的Cookie信息
            cookie.setDomain("www.fitbit.com"); // 设置Cookie的作用域
            cookie.setPath("/"); // 设置Cookie的路径
            cookieStore.addCookie(cookie);
            CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();

            String postData ="client_id="+clientId+"&response_type=code&scope=activity+heartrate+location+nutrition+oxygen_saturation+profile+respiratory_rate+settings+sleep+social+temperature+weight&state&prompt=none";
            HttpPost httpPost = new HttpPost(userAuthorizationUri);
            // 设置POST请求的Content-Type
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            // 设置POST请求的参数
            StringEntity entity = new StringEntity(postData, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode==302){
                Header locationHeader = response.getFirstHeader("Location");
                if (locationHeader != null) {
                    String redirectURL = locationHeader.getValue();
                    System.out.println("==================以下为fitbit服务信息===============");
                    System.out.println("重定向的路径：" + redirectURL);
                    code=redirectURL.substring(redirectURL.indexOf('=')+1).split("#")[0];
                    System.out.println("Authorize为"+code);

                } else {
                    System.out.println("未找到重定向路径");
                }

            }else {
                log.error("fitbit获取code失败");
            }
            CloseableHttpClient tokenHttpClient = HttpClients.createDefault();
            String tokenPostData = "grant_type=authorization_code&code="+code;
            HttpPost tokenHttpPost = new HttpPost(accessTokenUri);
            // 设置POST请求的Content-Type
            tokenHttpPost.setHeader("Authorization","Basic "+Base64Utils.encode((clientId+":"+clientSecret).getBytes()));
            tokenHttpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            // 设置POST请求的参数
            StringEntity tokenEntity = new StringEntity(tokenPostData, StandardCharsets.UTF_8);
            tokenHttpPost.setEntity(tokenEntity);
            CloseableHttpResponse tokenResponse = tokenHttpClient.execute(tokenHttpPost);
            BufferedReader reader = new BufferedReader(new InputStreamReader(tokenResponse.getEntity().getContent()));
            StringBuilder jsonResponse = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                jsonResponse.append(line);
            }
            System.out.println("返回的JSON数据：" + jsonResponse.toString());
            Gson gson = new Gson();
            Map<String,Object> map = gson.fromJson(jsonResponse.toString(), Map.class);
            access_token= (String) map.get("access_token");
            refresh_token= (String) map.get("refresh_token");
            token_type= (String) map.get("token_type");
            user_id= (String) map.get("user_id");
            System.out.println("access_token为"+access_token);
            System.out.println("refresh_token为"+refresh_token);
            System.out.println("token_type为"+token_type);
            System.out.println("user_id为"+user_id);
            System.out.println("==================fitbit服务信息结束===============");
        }catch (Exception e){
            log.error("获取fitbit的token失败！");
            e.printStackTrace();
        }

    }

    @Override
    public Equipment getEquipment() {
        Equipment equipment = new Equipment();
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            HttpGet httpGet = new HttpGet(apiUri+"/1/user/"+user_id+"/devices.json");
            httpGet.setHeader("Authorization",token_type+" "+access_token);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                int statusCode = response.getStatusLine().getStatusCode();

                // 获取返回的JSON数据
                if (statusCode >= 200 && statusCode < 300) {
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
                        StringBuilder jsonResponse = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            jsonResponse.append(line);
                        }
                        System.out.println("返回的JSON数据：" + jsonResponse.toString());
                        String substring = jsonResponse.substring(1, jsonResponse.length() - 1);
                        equipment = new Gson().fromJson(substring, Equipment.class);


                    }
                } else {
                    System.out.println("请求失败，状态码：" + statusCode);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return equipment;
    }

    @Override
    public RateZones getRateZones(String date) {
        RateZones rateZones = new RateZones();
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            HttpGet httpGet = new HttpGet(apiUri+"/1/user/"+user_id+"/activities/heart/date/"+date+"/1d.json");
            httpGet.setHeader("Authorization",token_type+" "+access_token);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                int statusCode = response.getStatusLine().getStatusCode();

                // 获取返回的JSON数据
                if (statusCode >= 200 && statusCode < 300) {
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
                        StringBuilder jsonResponse = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            jsonResponse.append(line);
                        }
                        System.out.println("返回的JSON数据：" + jsonResponse.toString());
                        String substring = jsonResponse.substring(jsonResponse.indexOf("heartRateZones")-1, jsonResponse.length() - 4);
                        System.out.println(substring);
                        rateZones = new Gson().fromJson("{"+substring+"}", RateZones.class);


                    }
                } else {
                    System.out.println("请求失败，状态码：" + statusCode);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rateZones;
    }

    @Override
    public String getBMI(String date) {
        String bmi="";
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            HttpGet httpGet = new HttpGet(apiUri+"/1/user/"+user_id+"/body/bmi/date/"+date+"/1d.json");
            httpGet.setHeader("Authorization",token_type+" "+access_token);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                int statusCode = response.getStatusLine().getStatusCode();

                // 获取返回的JSON数据
                if (statusCode >= 200 && statusCode < 300) {
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
                        StringBuilder jsonResponse = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            jsonResponse.append(line);
                        }
                        System.out.println("返回的JSON数据：" + jsonResponse.toString());
                        String substring = jsonResponse.substring(jsonResponse.indexOf("value")+8, jsonResponse.length() - 4);
                        System.out.println("bmi为"+substring);
                        bmi=substring;

                    }
                } else {
                    System.out.println("请求失败，状态码：" + statusCode);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bmi;
    }

    @Override
    public String getWeight(String date) {
        String weight="";
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            HttpGet httpGet = new HttpGet(apiUri+"/1/user/"+user_id+"/body/weight/date/"+date+"/1d.json");
            httpGet.setHeader("Authorization",token_type+" "+access_token);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                int statusCode = response.getStatusLine().getStatusCode();

                // 获取返回的JSON数据
                if (statusCode >= 200 && statusCode < 300) {
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
                        StringBuilder jsonResponse = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            jsonResponse.append(line);
                        }
                        System.out.println("返回的JSON数据：" + jsonResponse.toString());
                        String substring = jsonResponse.substring(jsonResponse.indexOf("value")+8, jsonResponse.length() - 4);
                        System.out.println("weight为"+substring);
                        weight=substring;

                    }
                } else {
                    System.out.println("请求失败，状态码：" + statusCode);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return weight;
    }

    @Override
    public String getCalories(String date) {
        String calories="";
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            HttpGet httpGet = new HttpGet(apiUri+"/1/user/"+user_id+"/activities/calories/date/"+date+"/1d.json");
            httpGet.setHeader("Authorization",token_type+" "+access_token);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                int statusCode = response.getStatusLine().getStatusCode();

                // 获取返回的JSON数据
                if (statusCode >= 200 && statusCode < 300) {
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
                        StringBuilder jsonResponse = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            jsonResponse.append(line);
                        }
                        System.out.println("返回的JSON数据：" + jsonResponse.toString());
                        String substring = jsonResponse.substring(jsonResponse.indexOf("value")+8, jsonResponse.length() - 4);
                        System.out.println("calories为"+substring);
                        calories=substring;

                    }
                } else {
                    System.out.println("请求失败，状态码：" + statusCode);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return calories;
    }

    @Override
    public String getFloors(String date) {
        String floors="";
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            HttpGet httpGet = new HttpGet(apiUri+"/1/user/"+user_id+"/activities/floors/date/"+date+"/1d.json");
            httpGet.setHeader("Authorization",token_type+" "+access_token);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                int statusCode = response.getStatusLine().getStatusCode();

                // 获取返回的JSON数据
                if (statusCode >= 200 && statusCode < 300) {
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
                        StringBuilder jsonResponse = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            jsonResponse.append(line);
                        }
                        System.out.println("返回的JSON数据：" + jsonResponse.toString());
                        String substring = jsonResponse.substring(jsonResponse.indexOf("value")+8, jsonResponse.length() - 4);
                        System.out.println("floors为"+substring);
                        floors=substring;

                    }
                } else {
                    System.out.println("请求失败，状态码：" + statusCode);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return floors;
    }

    @Override
    public String getSteps(String date) {
        String steps="";
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            HttpGet httpGet = new HttpGet(apiUri+"/1/user/"+user_id+"/activities/steps/date/"+date+"/1d.json");
            httpGet.setHeader("Authorization",token_type+" "+access_token);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                int statusCode = response.getStatusLine().getStatusCode();

                // 获取返回的JSON数据
                if (statusCode >= 200 && statusCode < 300) {
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
                        StringBuilder jsonResponse = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            jsonResponse.append(line);
                        }
                        System.out.println("返回的JSON数据：" + jsonResponse.toString());
                        String substring = jsonResponse.substring(jsonResponse.indexOf("value")+8, jsonResponse.length() - 4);
                        System.out.println("steps为"+substring);
                        steps=substring;

                    }
                } else {
                    System.out.println("请求失败，状态码：" + statusCode);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return steps;
    }

    @Override
    public String getDistance(String date) {
        String distance="";
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            HttpGet httpGet = new HttpGet(apiUri+"/1/user/"+user_id+"/activities/distance/date/"+date+"/1d.json");
            httpGet.setHeader("Authorization",token_type+" "+access_token);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                int statusCode = response.getStatusLine().getStatusCode();

                // 获取返回的JSON数据
                if (statusCode >= 200 && statusCode < 300) {
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
                        StringBuilder jsonResponse = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            jsonResponse.append(line);
                        }
                        System.out.println("返回的JSON数据：" + jsonResponse.toString());
                        String substring = jsonResponse.substring(jsonResponse.indexOf("value")+8, jsonResponse.length() - 4);
                        System.out.println("distance为"+substring);
                        distance=substring;

                    }
                } else {
                    System.out.println("请求失败，状态码：" + statusCode);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return distance;
    }

    @Override
    public String getElevation(String date) {
        String elevation="";
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

            HttpGet httpGet = new HttpGet(apiUri+"/1/user/"+user_id+"/activities/elevation/date/"+date+"/1d.json");
            httpGet.setHeader("Authorization",token_type+" "+access_token);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                int statusCode = response.getStatusLine().getStatusCode();

                // 获取返回的JSON数据
                if (statusCode >= 200 && statusCode < 300) {
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
                        StringBuilder jsonResponse = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            jsonResponse.append(line);
                        }
                        System.out.println("返回的JSON数据：" + jsonResponse.toString());
                        String substring = jsonResponse.substring(jsonResponse.indexOf("value")+8, jsonResponse.length() - 4);
                        System.out.println("elevation为"+substring);
                        elevation=substring;

                    }
                } else {
                    System.out.println("请求失败，状态码：" + statusCode);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return elevation;
    }


}
